import csv
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from datetime import datetime
from database.crud import get_events, add_event

def export_events(file_path=None):
    """导出所有事件到CSV文件"""
    if not file_path:
        file_path = filedialog.asksaveasfilename(
            defaultextension=".csv",
            filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
            title="Save Events as CSV"
        )
        if not file_path:
            return False
    
    events = get_events()
    with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        # 写入CSV标题
        writer.writerow([
            "ID", "Title", "Description", "Event Time", 
            "Category", "Recurring Type", "Recurring End Date"
        ])
        
        # 写入事件数据
        for event in events:
            event_id, title, desc, event_time, _, _, category, recurring_type, recurring_end_date = event
            writer.writerow([
                event_id,
                title,
                desc.replace('\n', ' ').replace(',', ' ')[:255],  # 防止CSV格式错误
                event_time,
                category,
                recurring_type or "None",
                recurring_end_date or ""
            ])
    
    messagebox.showinfo("Export Successful", f"Events exported to:\n{file_path}")
    return True

def import_events(file_path=None):
    """从CSV文件导入事件"""
    if not file_path:
        file_path = filedialog.askopenfilename(
            filetypes=[("CSV files", "*.csv"), ("All files", "*.*")],
            title="Select Events CSV File"
        )
        if not file_path:
            return False
    
    try:
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            count = 0
            
            for row in reader:
                # 验证必需字段
                if not all(k in row for k in ["Title", "Event Time", "Category"]):
                    continue
                
                # 导入事件
                add_event(
                    title=row["Title"],
                    description=row.get("Description", ""),
                    event_time=row["Event Time"],
                    reminder_time=None,  # 导入时默认无提醒
                    category=row["Category"],
                    recurring_type=row.get("Recurring Type", "None"),
                    recurring_end_date=row.get("Recurring End Date", "")
                )
                count += 1
            
            messagebox.showinfo(
                "Import Successful", 
                f"Imported {count} events from {os.path.basename(file_path)}"
            )
            return True
            
    except Exception as e:
        messagebox.showerror("Import Error", f"Failed to import events:\n{str(e)}")
        return False